//
//  CellDetailViewController.m
//  TextApplication
//
//  Created by dllo on 16/9/9.
//  Copyright © 2016年 yh. All rights reserved.
//

#import "CellDetailViewController.h"
#import "TAMacro.h"
#import "TextView.h"
#import "ZWYNetTool.h"
#import "TableCellDetailCollectionViewCell.h"

#import "UIImageView+WebCache.h"

#import "LikeDetailViewController.h"

#import "CollectionFirst.h"
#import "CollectionViewDataModel.h"
#import "CollectionViewItems.h"
#import "CollectionViewBrand.h"

#import "MJRefresh.h"
#import "MBProgressHUD.h"

#import "CollectView.h"

@interface CellDetailViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) UIButton *choiceButton;

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, copy) NSString *urlString;
@property (nonatomic, copy) NSString *secUrlStr;

@property (nonatomic, strong) CollectionFirst *first;
@property (nonatomic, strong) UITableView *choiceTableView;

@property (nonatomic, copy) NSString *IDStr;

@property (nonatomic, strong) UILabel *choiceLabel;

@property (nonatomic, assign) NSInteger page;

@property (nonatomic, assign) NSInteger num;
@property (nonatomic, copy) NSString *priceStr;

@property (nonatomic, copy) NSString *str1;
@property (nonatomic, copy) NSString *str2;
@property (nonatomic, copy) NSString *str3;

@property (nonatomic, strong) NSMutableArray <CollectionViewItems *>*dataArray;
@property (nonatomic, strong) CollectView *collectView;

@end

@implementation CellDetailViewController

- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBar.hidden = NO;
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithWhite:0.094 alpha:1.000];
}

//- (void)viewWillDisappear:(BOOL)animated {
//    self.navigationController.navigationBar.hidden = YES;
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.page = 1;
    [self createBarButton];
    [self createCollectionView];
    [self createChoiceTableView];
    if (self.textStr.length != 0) {
        self.collectionView.frame =CGRectMake(0, 0, WIDTH, HEIGHT - 108);
        [self createSearchData];
    }else if (self.giftURL.length == 0) {
        [self createChoiceButton];

        [self createData];
    } else {
//        self.choiceButton.hidden = YES;
        self.collectionView.frame =CGRectMake(0, 0, WIDTH, HEIGHT - 108);
        [self createGiftData];
    }
}

- (void)createGiftData {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.label.text = NSLocalizedString(@"loading", @"HUD loading title");

    self.num = 27;
    if (self.page ==1) {
        self.dataArray = [NSMutableArray array];
    }
    NSString *str1 = @"http://mobile.iliangcang.com/goods/goodsList?a=b&page=";
    NSString *str3 = @"&list_id=";
    NSString *str2 = @"&count=10&app_key=iPhone&v=3.0.0&sig=254F2CCC-7E43-4833-A27D-7D12702F5981";
    NSString *str = [[[[str1 stringByAppendingString:[NSString stringWithFormat:@"%ld", self.page]] stringByAppendingString:str3] stringByAppendingString:self.giftURL]stringByAppendingString:str2];
    NSDictionary *headDic = @{@"Host": @"mobile.iliangcang.com", @"Proxy-Connection": @"keep-alive", @"Accept": @"*/*", @"Accept-Language": @"zh-Hans-CN;q=1, en-CN;q=0.9", @"Connection": @"keep-alive", @"User-Agent": @"iLiangCang/3.0.0 (iPhone; iOS 9.2.1; Scale/2.00) Paros/3.2.13"};
    NSLog(@"%@", str);
    [ZWYNetTool GET:str andBody:nil andHeader:headDic andResponse:ZWYJSON andSuccessBlock:^(id result) {
        self.first = [CollectionFirst modelWithDic:result];
        for (CollectionViewItems *item in self.first.data.items) {
            [self.dataArray addObject:item];
        }
        if (self.dataArray.count != 0) {
            [hud hideAnimated:YES afterDelay:0.5];
        }
        self.page = self.page + 1;
        [self.collectionView reloadData];
    } andFailureBlock:^(NSError *error) {
        NSLog(@"失败");
        NSLog(@"%@", error);
    }];
}

// 筛选价格的tableView
- (void)createChoiceTableView {
    self.choiceTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 44, WIDTH, 0)];
    self.choiceTableView.alpha = 0.5;
    self.choiceTableView.delegate = self;
    self.choiceTableView.dataSource = self;
    self.choiceTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.choiceTableView];
    [self.choiceTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"reuse"];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 6;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSArray *array = @[@"全部", @"0-200", @"201-500", @"501-1000", @"1001-3000", @"3000以上"];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.textLabel.text = array[indexPath.row];
    cell.textLabel.textColor = [UIColor whiteColor];
    cell.backgroundColor = [UIColor blackColor];
    return cell;
}

- (void)handleStr {
    NSString *str1 = @"http://mobile.iliangcang.com/goods/goodsShare?a=b&page=";
    NSString *str3 = @"&count=10&cat_code=";
    NSString *str2 = @"&coverId=1&app_key=iPhone&v=3.0.0&sig=254F2CCC-7E43-4833-A27D-7D12702F5981";
    [self handleIDStr];
    self.urlString = [[[[str1 stringByAppendingString:[NSString stringWithFormat:@"%ld", self.page]] stringByAppendingString:str3] stringByAppendingString:self.IDStr] stringByAppendingString:str2];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    NSLog(@"%f", self.collectionView.contentOffset.y);
    if (self.collectionView.contentOffset.y < -200) {
        self.collectionView.contentOffset = CGPointMake(0, 0);
    }
    
}

// 下拉刷新数据
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if (self.collectionView.contentOffset.y < 0) {
        [self.dataArray removeAllObjects];
        self.page = 1;
//        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//        hud.label.text = NSLocalizedString(@"loading", @"HUD loading title");
        self.page = 1;
        if (self.num == 37) {
            [self createSearchData];
        }else if (self.num == 7) {
            [self createData];
        } else if (self.num == 17){
            [self createPriceData];
        } else {
            [self createGiftData];
        }
//        if (self.dataArray.count != 0) {
//            [hud hideAnimated:YES afterDelay:1];
//        }
        NSLog(@"%@", self.dataArray);
    }
  
}

// 上拉加载 不是价格筛选
- (void)upLoad {
    self.collectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        // 利用num全局变量来判断要走哪个网络请求
        if (self.num == 37) {
            [self createSearchData];
        }else if (self.num == 7) {
            [self createData];
        } else if (self.num == 17){
            // 价格筛选的上拉刷新
            [self createPriceData];
        } else {
            [self createGiftData];
        }
        [self.collectionView.mj_footer endRefreshing];
    }];
}


- (void)createPriceData {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.label.text = NSLocalizedString(@"loading", @"HUD loading title");

    self.num = 17;
    // 获取的是价格筛选的tableView数据
       self.urlString = [[[[self.str1 stringByAppendingString:[NSString stringWithFormat:@"%ld", self.page]] stringByAppendingString:self.str2] stringByAppendingString: self.IDStr] stringByAppendingString:self.str3];
        NSDictionary *headDic = @{@"Host": @"mobile.iliangcang.com", @"Proxy-Connection": @"keep-alive", @"Accept": @"*/*", @"Accept-Language": @"zh-Hans-CN;q=1, en-CN;q=0.9", @"Connection": @"keep-alive", @"User-Agent": @"iLiangCang/3.0.0 (iPhone; iOS 9.2.1; Scale/2.00) Paros/3.2.13"};
        [ZWYNetTool GET:self.urlString andBody:nil andHeader:headDic andResponse:ZWYJSON andSuccessBlock:^(id result) {
            if (self.page == 1) {
                self.dataArray = [NSMutableArray array];
            }

            self.first = [CollectionFirst modelWithDic:result];
            for (CollectionViewItems *item in self.first.data.items) {
                [self.dataArray addObject:item];
            }
            if (self.dataArray.count != 0) {
                [hud hideAnimated:YES afterDelay:0.5];
            }
            self.page = self.page + 1;
            [self.collectionView reloadData];
        } andFailureBlock:^(NSError *error) {
        }];
}

- (void)createSearchData {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.label.text = NSLocalizedString(@"loading", @"HUD loading title");

    self.num = 37;
    NSString *str1 = @"http://mobile.iliangcang.com/goods/search?a=b&coverId=1&keyword=";
    NSString *str2 = @"&page=";
    NSString *str3 = @"&count=12&toGoodsList=1&app_key=iPhone&v=3.0.0&sig=254F2CCC-7E43-4833-A27D-7D12702F5981";
    NSString *str = [[[[str1 stringByAppendingString:self.textStr] stringByAppendingString:str2] stringByAppendingString:[NSString stringWithFormat:@"%ld", self.page]] stringByAppendingString:str3];
    
    NSDictionary *headDic = @{@"Host": @"mobile.iliangcang.com", @"Proxy-Connection": @"keep-alive", @"Accept": @"*/*", @"Accept-Language": @"zh-Hans-CN;q=1, en-CN;q=0.9", @"Connection": @"keep-alive", @"User-Agent": @"iLiangCang/3.0.0 (iPhone; iOS 9.2.1; Scale/2.00) Paros/3.2.13"};
    [ZWYNetTool GET:str andBody:nil andHeader:headDic andResponse:ZWYJSON andSuccessBlock:^(id result) {
        if (self.page ==1) {
            self.dataArray = [NSMutableArray array];
        }
        self.first = [CollectionFirst modelWithDic:result];
        for (CollectionViewItems *item in self.first.data.items) {
            [self.dataArray addObject:item];
        }
        if (self.dataArray.count != 0) {
            [hud hideAnimated:YES afterDelay:0.5];
        }
        self.page = self.page + 1;
        [self.collectionView reloadData];
    } andFailureBlock:^(NSError *error) {
    }];
}


- (void)createData {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.label.text = NSLocalizedString(@"loading", @"HUD loading title");

    // 获取的是点击之前半透明分类tableView的数据 而不是点击价格筛选的tableView 一开始点击tableView cell时的urlString为空 走第一个网络请求 当点击价格筛选的tableView cell时urlString被处理了  不为空 走第二个网络请求
    self.num = 7;
        [self handleStr];

        NSDictionary *headDic = @{@"Host": @"mobile.iliangcang.com", @"Proxy-Connection": @"keep-alive", @"Accept": @"*/*", @"Accept-Language": @"zh-Hans-CN;q=1, en-CN;q=0.9", @"Connection": @"keep-alive", @"User-Agent": @"iLiangCang/3.0.0 (iPhone; iOS 9.2.1; Scale/2.00) Paros/3.2.13"};
        [ZWYNetTool GET:self.urlString andBody:nil andHeader:headDic andResponse:ZWYJSON andSuccessBlock:^(id result) {
            if (self.page ==1) {
                self.dataArray = [NSMutableArray array];
            }
            
            self.first = [CollectionFirst modelWithDic:result];
            for (CollectionViewItems *item in self.first.data.items) {
                [self.dataArray addObject:item];
            }
                       if (self.dataArray.count != 0) {
                [hud hideAnimated:YES];
            }
            NSLog(@"%@", self.dataArray);
            if (self.dataArray.count != 0) {
                [hud hideAnimated:YES afterDelay:0.5];
            }
            
            self.page = self.page + 1;
            [self.collectionView reloadData];
        } andFailureBlock:^(NSError *error) {
            NSLog(@"失败");
        }];
}

- (void)handleIDStr{
    if (self.urlStr.length == 2) {
        self.urlStr = [@"00" stringByAppendingString:self.urlStr];
    } else if (self.urlStr.length == 3) {
        self.urlStr = [@"0" stringByAppendingString:self.urlStr];
    } else {
        self.urlStr = self.urlStr;
    }
    
    if (self.secID.length == 2) {
        self.secID = [@"00" stringByAppendingString:self.secID];
    } else if (self.urlStr.length == 3) {
        self.secID = [@"0" stringByAppendingString:self.secID];
    } else {
        self.secID = self.secID;
    }
    self.IDStr = [self.secID stringByAppendingString:self.urlStr];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self.dataArray removeAllObjects];
    self.page = 1;
    // 筛选价格的tableView
    if (indexPath.row == 0) {
        self.choiceLabel.text = @"价格筛选";
        self.str1 = @"http://mobile.iliangcang.com/goods/goodsShare?a=b&page=";
        self.str2 = @"&count=10&cat_code=";
        self.str3 = @"&coverId=1&app_key=iPhone&v=3.0.0&sig=254F2CCC-7E43-4833-A27D-7D12702F5981";
        [self handleIDStr];
        self.urlString = [[[[self.str1 stringByAppendingString:[NSString stringWithFormat:@"%ld", self.page]] stringByAppendingString:self.str2] stringByAppendingString: self.IDStr] stringByAppendingString:self.str3];
        [self createPriceData];

    } else if (indexPath.row == 1) {
        self.choiceLabel.text = @"0-200";
        self.str1 = @"http://mobile.iliangcang.com/goods/goodsShare?a=b&coverId=1&page=";
        self.str2 = @"&count=10&max=200&orderby=price&cat_code=";
        self.str3 = @"&app_key=iPhone&v=3.0.0&sig=254F2CCC-7E43-4833-A27D-7D12702F5981";
        [self handleIDStr];
        self.urlString = [[[[self.str1 stringByAppendingString:[NSString stringWithFormat:@"%ld", self.page]] stringByAppendingString:self.str2] stringByAppendingString:self.IDStr] stringByAppendingString:self.str3];
        [self createPriceData];
    } else if (indexPath.row == 2) {
        self.choiceLabel.text = @"201-500";

    self.str1 = @"http://mobile.iliangcang.com/goods/goodsShare?a=b&coverId=1&min=201&page=";
    self.str2 = @"&orderby=price&cat_code=";
    self.str3 = @"&max=500&count=10&app_key=iPhone&v=3.0.0&sig=254F2CCC-7E43-4833-A27D-7D12702F5981";
        
    [self handleIDStr];
    self.urlString = [[[[self.str1 stringByAppendingString:[NSString stringWithFormat:@"%ld", self.page]] stringByAppendingString:self.str2] stringByAppendingString:self.IDStr] stringByAppendingString:self.str3];
    [self createPriceData];
    } else if (indexPath.row == 3) {
        self.choiceLabel.text = @"501-1000";

        self.str1 = @"http://mobile.iliangcang.com/goods/goodsShare?a=b&coverId=1&min=501&page=";
        self.str2 = @"&orderby=price&cat_code=";
        self.str3 = @"&max=1000&count=10&app_key=iPhone&v=3.0.0&sig=254F2CCC-7E43-4833-A27D-7D12702F5981";
        [self handleIDStr];
        self.urlString = [[[[self.str1 stringByAppendingString:[NSString stringWithFormat:@"%ld", self.page]] stringByAppendingString:self.str2] stringByAppendingString:self.IDStr] stringByAppendingString:self.str3];
        [self createPriceData];

    } else if (indexPath.row == 4) {
        self.choiceLabel.text = @"1001-3000";
        self.str1 = @"http://mobile.iliangcang.com/goods/goodsShare?a=b&coverId=1&min=1001&page=";
        self.str2 = @"&orderby=price&cat_code=";
        self.str3 = @"&max=3000&count=10&app_key=iPhone&v=3.0.0&sig=254F2CCC-7E43-4833-A27D-7D12702F5981";
        [self handleIDStr];
        self.urlString = [[[[self.str1 stringByAppendingString:[NSString stringWithFormat:@"%ld", self.page]] stringByAppendingString:self.str2] stringByAppendingString:self.IDStr] stringByAppendingString:self.str3];
        [self createPriceData];
    } else {
        self.choiceLabel.text = @"3000以上";
        self.str1 = @"http://mobile.iliangcang.com/goods/goodsShare?a=b&min=3000&page=";
        self.str2 = @"&count=10&orderby=price&cat_code=";
        self.str3 = @"&coverId=1&app_key=iPhone&v=3.0.0&sig=254F2CCC-7E43-4833-A27D-7D12702F5981";
        self.urlString = [[[[self.str1 stringByAppendingString:[NSString stringWithFormat:@"%ld", self.page]] stringByAppendingString:self.str2] stringByAppendingString:self.IDStr] stringByAppendingString:self.str3];
        [self createPriceData];
    }
    if (self.choiceTableView.frame.size.height == 0) {
        [UIView animateWithDuration:0.5 animations:^{
            self.choiceTableView.frame = CGRectMake(0, 44, WIDTH, 270);
        }];
    } else {
        [UIView animateWithDuration:1 animations:^{
            self.choiceTableView.frame = CGRectMake(0, 44, WIDTH, 0);
        }];
    }
}

- (void)createChoiceButton {
    self.choiceButton = [UIButton buttonWithType: UIButtonTypeSystem];
    self.choiceButton.frame = CGRectMake(10, 0, WIDTH - 20, 44);
    self.choiceButton.backgroundColor = [UIColor whiteColor];
    [self.choiceButton addTarget:self action:@selector(choiceClick:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:self.choiceButton];
    self.choiceLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 120, 44)];
    self.choiceLabel.text = @"价格筛选";
    self.choiceLabel.textColor = [UIColor grayColor];
    self.choiceLabel.font = [UIFont systemFontOfSize:12];
    [self.choiceButton addSubview:self.choiceLabel];
    
    UIImageView *picImageView = [[UIImageView alloc] initWithFrame:CGRectMake(WIDTH - 50, 10, 20, 24)];
    picImageView.image = [UIImage imageNamed:@"29"];
    [self.choiceButton addSubview:picImageView];
}

- (void)choiceClick:(UIButton *)button {
    if (self.choiceTableView.frame.size.height == 0) {
        [UIView animateWithDuration:0.5 animations:^{
            self.choiceTableView.frame = CGRectMake(0, 44, WIDTH, 270);
        }];
    } else {
        [UIView animateWithDuration:1 animations:^{
            self.choiceTableView.frame = CGRectMake(0, 44, WIDTH, 0);
        }];
    }
}

- (void)createBarButton {
    self.title = @"商店";

    UIButton *left = [TextView createButtonWithImage:[UIImage imageNamed:@"10"]];
    [left addTarget:self action:@selector(backClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:left];
    
}

- (void)backClick:(UIButton *)button {
    [self.navigationController popToRootViewControllerAnimated:NO];
}

- (void)createCollectionView {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake((WIDTH - 30)/ 2, (WIDTH - 30)/ 2 + 100);
    layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 44, WIDTH, HEIGHT - 152) collectionViewLayout:layout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.view addSubview:self.collectionView];
    [self.collectionView registerClass:[TableCellDetailCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    [self upLoad];
    TableCellDetailCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    cell.collectData = self.dataArray[indexPath.row];
    cell.backgroundColor = [UIColor whiteColor];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    self.collectView = [[CollectView alloc] init];
    self.collectView.imageID = self.dataArray[indexPath.row].goods_id;
    LikeDetailViewController *detailVC = [[LikeDetailViewController alloc] init];
    detailVC.goodID = self.dataArray[indexPath.row].goods_id;
    [self.navigationController pushViewController:detailVC animated:NO];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
